Functions (cont.): jal and jr

JAL:

JR:

To mark a function, use a label as we have seen before

Argument and return (value) registers:

Example:

Convert the following code. The first parameter is in $a0, second parameter is in $a1. Answer should be placed in $v0.

int sum(int a, int b) { return a + b; }

Solution (MIPS):

sum:
    add $t0, $a0, $a1 # a+b
    add $v0, $zero, $t0 # and place in return register
    jr $ra

...

# function usage

addi $s0, $zero, 8
addi $a0, $zero, 4
addi $a1, $zero, 5
jal sum
add $t1, $v0, $s0

In memory, there may be a "halt" instruction before function code space so that functions are not executed except by jumping directly to them:

# ...program code...

HALT

func1: 
    ...
    jr $ra

func2:
    ...
    jr $ra

Function calling conventions

But what if registers used in a function are storing things outside the function? Then the registers will be overwritten, because registers are global variables. For instance, in the previous example, if instead of $s0 we had set $t0 to some value, it would have been overwritten during the function call.

Solution: function calling conventions.

Convention:

Note:

In this class, we should assume that any function we are given (e.g. on an exam) follows the function calling convention correctly.